package com.t3rik.mes.emp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.t3rik.common.utils.DateUtils;
import com.t3rik.mes.emp.domain.EmpAttendanceRecord;
import com.t3rik.mes.emp.domain.EmpPieceSalaryDetails;
import com.t3rik.mes.emp.domain.EmpSalary;
import com.t3rik.mes.emp.domain.vo.EmpPieceSalaryDetailsVo;
import com.t3rik.mes.emp.mapper.EmpSalaryMapper;
import com.t3rik.mes.emp.service.IEmpAttendanceRecordService;
import com.t3rik.mes.emp.service.IEmpPieceSalaryDetailsService;
import com.t3rik.mes.emp.service.IEmpSalaryService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 工资总表Service业务层处理
 *
 * @author ykh
 * @date 2025-02-19
 */
@Service
public class EmpSalaryServiceImpl  extends ServiceImpl<EmpSalaryMapper, EmpSalary>  implements IEmpSalaryService
{
    @Autowired
    private EmpSalaryMapper empSalaryMapper;

    @Autowired
    private IEmpPieceSalaryDetailsService empPieceSalaryDetailsService;

    @Autowired
    private IEmpAttendanceRecordService empAttendanceRecordService;
    /**
     * 计算当年的总薪资
     * @param
     * @return
     */
    @Override
    public List<EmpSalary> computeSalary(List<EmpSalary> empSalaryList) {
        //获取当前年份第一天与最后一天
        String date = empSalaryList.get(0).getYear();
        String year = date.split("-")[0];
        LocalDate startTime = LocalDate.of(Integer.parseInt(year), 1, 1);
        LocalDate endTime = LocalDate.of(Integer.parseInt(year), 12, 31);

        //以用户id构造Map
        Map<Long, EmpSalary> empSalaryMap = new HashMap<>();
        for (EmpSalary item : empSalaryList) {
            empSalaryMap.put(item.getUserId(), item);
        }

        List<EmpSalary> result = new ArrayList<>();
        //到详情表查询时间在该年度内的薪资详情
        List<EmpPieceSalaryDetails> details = empPieceSalaryDetailsService.getListByYear(startTime, endTime);
        //按照用户id分组
        Map<Long, List<EmpPieceSalaryDetails>> salaryDetailMap = new HashMap<>();
        for (EmpPieceSalaryDetails detail : details){
            salaryDetailMap.computeIfAbsent(detail.getUserId(), k -> new ArrayList<>()).add(detail);
        }

        //到详情表查询时间在该年度内的考勤天数
        List<EmpAttendanceRecord> attendanceRecords = empAttendanceRecordService.getRecordByYear(startTime, endTime);
        //按照user_Id分组
        Map<Long, EmpAttendanceRecord> attendanceRecordMap = new HashMap<>();
        for (EmpAttendanceRecord attendanceRecord : attendanceRecords){
            attendanceRecordMap.put(attendanceRecord.getUserId(), attendanceRecord);
        }

        for (Map.Entry<Long, List<EmpPieceSalaryDetails>> entry : salaryDetailMap.entrySet()) {
            EmpSalary salary = new EmpSalary();
            Long userId = entry.getKey();
            List<EmpPieceSalaryDetails> detailsList = entry.getValue();
            //计算该员工的工资
            List<EmpPieceSalaryDetailsVo> empPieceSalaryDetailsVos
                    = empPieceSalaryDetailsService.computeEmpSalary(detailsList);
            EmpSalary rawData = empSalaryMap.get(userId);
            if(Objects.isNull(rawData)){
                continue;
            }
            salary.setId(rawData.getId());
            salary.setSettlementStatus(rawData.getSettlementStatus());
            salary.setLastSettledTime(rawData.getLastSettledTime());
            salary.setCreateTime(rawData.getCreateTime());
            salary.setUserId(userId);
            salary.setYear(date);
            salary.setTotalCountPrice(new BigDecimal(0));
            salary.setTotalPrice(new BigDecimal(0));
            salary.setDayPrice(new BigDecimal(0));
            salary.setNightPrice(new BigDecimal(0));
            //计算计件工资
            for (EmpPieceSalaryDetailsVo item : empPieceSalaryDetailsVos) {
                salary.setUserName(item.getUserName());

                //计件总工资（不含奖励）
                salary.setTotalCountPrice(salary.getTotalCountPrice().add(item.getCountPrice()));
                //计件总工资（含奖励）
                salary.setTotalPrice(salary.getTotalPrice().add(item.getTotalPrice()));
            }

            //计算出勤工资
            EmpAttendanceRecord attendanceRecord = attendanceRecordMap.get(userId);
            if (Objects.nonNull(attendanceRecord)) {
                // 白班工资 = 白班天数 * 2
                salary.setDayPrice(new BigDecimal(attendanceRecord.getDayCount() * 2));
                // 夜班工资 = 夜班天数 * 1
                salary.setNightPrice(new BigDecimal(attendanceRecord.getNightCount()));
            }
            //最终工资 = 计件总工资 + 白班工资 + 夜班工资
            BigDecimal finalPrice = salary.getTotalPrice().add(salary.getDayPrice()).add(salary.getNightPrice());
            salary.setFinalPrice(finalPrice);
            salary.setSettledPrice(rawData.getSettledPrice());
            salary.setUnsettledPrice(finalPrice.subtract(salary.getSettledPrice()));
            result.add(salary);
        }
        //获取代理类
        EmpSalaryServiceImpl proxy = (EmpSalaryServiceImpl) AopContext.currentProxy();
        proxy.updateBatchById(result);
        return result;
    }

    @Override
    public EmpSalary selectEmpSalaryByUserId(Long userId, LocalDateTime year) {
        return empSalaryMapper.selectByUserId(userId, year);
    }
}
